package com.company.nuwa.common.utils;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;
import com.company.nuwa.common.enumration.GlobalBizCode;
import com.company.nuwa.common.exception.BizException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * <p>字段验工具类</p >
 *
 * @author Nikola Tesla
 * @version 1.0
 * @date 2020/11/15 14:59
 */
public interface ValidatorUtils {


    /**
     * 是否有效身份证号
     *
     * @param value
     * @return
     */
    static boolean isValidCard(String value) {
        return IdcardUtil.isValidCard(value);
    }

    /**
     * 是否有效移动电话
     *
     * @param value
     * @return
     */
    static boolean isValidMobile(String value) {
        return Validator.isMatchRegex(Validator.MOBILE, value);
    }

    /**
     * 是否是有效生日
     *
     * @param value
     * @return
     */
    static boolean isBirthDay(String value) {
        return Validator.isBirthday(value);
    }

    /**
     * 手动校验参数
     *
     * @param source
     */
    static void validate(@Valid Object source) {
        Set<ConstraintViolation<@Valid Object>> validateSet = Validation.buildDefaultValidatorFactory()
                .getValidator()
                .validate(source, new Class[0]);
        if (!CollectionUtils.isEmpty(validateSet)) {
            String messages = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + "；" + m2)
                    .orElse(GlobalBizCode.ILLEGAL_ARGUMENT.getMessage());
            throw new BizException(GlobalBizCode.ILLEGAL_ARGUMENT.getCode(), messages);
        }
    }

}
